#include "threadpool.h"

ThreadPool::ThreadPool(int threadnums)
{
    for(int i = 0; i < threadnums; i++)
    {
        // workers.emplace_back([this](){this->worker();});
        QThread* thread = QThread::create([this](){ this->worker(); });
        workers.append(thread);
        thread->start();
    }
    m_isstop = false;
}

ThreadPool::~ThreadPool()
{
    {
        QMutexLocker locker(&m_mtx);
        m_isstop = true;
    }
    //通知所有阻塞中的线程
    m_condition.wakeAll();

    //确保线程执行完成
    foreach (QThread *thread, workers) {
        thread->wait();//等待线程自然结束
        delete thread;
    }

}

void ThreadPool::worker()
{
    while(true)
    {
        function<void()> task;
        {
            QMutexLocker locker(&m_mtx);

            while(!m_isstop && this->myque.isEmpty())//当线程池运行中且队列为空时等待条件变量
                m_condition.wait(&m_mtx);


            if (m_isstop && this->myque.isEmpty()) // 线程停止并且队列为空没有剩余任务时退出
                return;

            task = this->myque.dequeue();//从任务队列中取出一个任务
        }

        if(task)
            task();
    }
}
